﻿using System;
using EmbeddedSharp.Core;
namespace Zove.Runtime.Core.InferencingStrategy {

    /// <summary>
    /// The abstract strategy
    /// </summary>
    public abstract class AbstractInferencingStrategy : IInferencingStrategy {

        /// <summary>
        /// Default constructor
        /// </summary>
        public AbstractInferencingStrategy() {
            Enable = true;
        }

        #region IInferencingStrategy Members

        /// <summary>
        /// The name
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Priority
        /// </summary>
        /// <returns>the priority</returns>
        public int Priority { get; set; }

        /// <summary>
        /// Run the alogrithm
        /// </summary>
        /// <param name="zoveObject">the model instance</param>
        public abstract void Infer(ZoveObject zoveObject);

        /// <summary>
        /// evaluate an expression
        /// </summary>
        /// <param name="sf">solved factor</param>
        /// <returns>the result</returns>
        public virtual double Evaluate(SolvedFactor sf) {
            try {
                object obj = sf.Rule.Root.Evaluate();
                if (obj == null) {
                    throw new NullReferenceException("The evaluated result is null.");
                }

                sf.Factor.Value = Convert.ToDouble(obj);
            } catch (DivideByZeroException ex) {
                Utils.Debugging(ex);
                return 0;
            } catch (Exception ex) {
            }

            return sf.Factor.Value;
        }

        /// <summary>
        /// Enable or disable the strategy
        /// </summary>
        public bool Enable { get; set; }

        #endregion
    }
}
